﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using SimpleRest.Core.Routing;
using System.Runtime.Serialization;
using System.Xml.Serialization;
using System.Xml;
using SimpleRest.Core.Extensions.Documentation;

namespace SimpleRest.Core.Extensions.Media
{
    [GeneralDescription("Xml media type support.")]
    public class XmlMediaTypeFormatter : IMediaTypeFormatter
    {
        public bool IsMediaFormatted { get; set; }

        public List<Type> PrimitiveTypes = new List<Type>()
            {
                typeof(Int16),
                typeof(Int32),
                typeof(Int64),
                typeof(double),
                typeof(float),
                typeof(char),
                typeof(Guid),
                typeof(string),
                typeof(byte),
                typeof(UInt16),
                typeof(UInt32),
                typeof(UInt64),
                typeof(DateTime),
                typeof(bool),
                typeof(decimal),
                typeof(object)
            };

        public IEnumerable<string> SupportedMediaTypes
        {
            get
            {
                return new List<string>()
                {
                    "application/xml",
                    "text/xml"
                };
            }
        }

        public Stream Serialize(object obj)
        {
            System.IO.MemoryStream ms = new System.IO.MemoryStream();

            System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(obj.GetType());
            XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.OmitXmlDeclaration = true;
            settings.Indent = IsMediaFormatted;
            settings.NewLineHandling = NewLineHandling.None;
            StringWriter StringWriter = new StringWriter();
            XmlWriter writer = XmlWriter.Create(StringWriter, settings);
            namespaces.Add(string.Empty, string.Empty);
            ser.Serialize(writer, obj, namespaces);
            ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(StringWriter.ToString()));

            return ms;
        }

        public object DeSerialize(Stream item, Type type)
        {
            if (item == null || item.Length == 0 || type == null)
                return null;

            System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(type);
            object obj = ser.Deserialize(item);
            return obj;
        }

        public bool CanSerialize(Type type)
        {
            if (type == null) return true;
            return true;
        }

        public bool CanDeserialize(Type type)
        {
            if (type == null) return true;
            return true;
        }
    }
}
